/**
 * Copyright (c) 2021-2028, iron.guo 郭成杰 (jiedreams@sina.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xdl.modules.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.beluga.core.annotation.BelugaController;
import com.beluga.core.response.ResponseResult;
import com.xdl.modules.dto.WechatLoginDto;
import com.xdl.modules.dto.WechatUserDto;
import com.xdl.modules.model.WxLoginModel;
import com.xdl.modules.service.WxUserService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * @Author iron.guo
 * @Date 2022/4/21
 * @Description
 */
@AllArgsConstructor
@BelugaController("/wx/login")
public class LoginController {

    private WxUserService userService;

    private WxMaService wxMaService;
    /**
     * 微信登陆接口
     * @param user
     * @return
     */
    @PostMapping("loginWithWechat")
    public ResponseResult<WechatUserDto> loginWithWechat(@RequestBody WechatLoginDto user) throws Exception {
        WechatUserDto result=userService.loginWithWechat(user);
        return ResponseResult.Success(result);
    }

    /**
     * 微信获取手机号
     * @param model
     * @return
     */
    @PostMapping("getPhoneNumber")
    public ResponseResult<WxMaPhoneNumberInfo> getPhoneNumber(@RequestBody WxLoginModel model) throws Exception {
        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(model.getCode());
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(sessionInfo.getSessionKey(), model.getEncryptedData(), model.getIv());
        return ResponseResult.Success(phoneNoInfo);
    }

}
